<template>
  <view class="repair-container">
    <!-- 服务说明区域 -->
    <view class="intro-section">
      <view class="intro-content">
        <u-icon name="tools" color="#409eff" size="24"></u-icon>
        <text class="intro-text">请详细填写报修信息，我们会尽快为您处理</text>
      </view>
    </view>

    <!-- 报修表单 -->
    <view class="form-container">
      <u-form :model="formData" ref="formRef" :rules="rules">
        <!-- 报修类型 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="list" color="#409eff" size="16"></u-icon>
            <text>报修类型</text>
            <text class="required">*</text>
          </view>
          <view class="type-grid">
            <view 
              v-for="type in repairTypes" 
              :key="type.value"
              class="type-item"
              :class="{ active: formData.repairType === type.value }"
              @click="selectRepairType(type.value)"
            >
              <u-icon :name="getTypeIcon(type.value)" color="currentColor" size="20"></u-icon>
              <text>{{ type.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 报修标题 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="edit-pen" color="#409eff" size="16"></u-icon>
            <text>报修标题</text>
            <text class="required">*</text>
          </view>
          <u-input 
            v-model="formData.title"
            placeholder="请输入报修标题"
            maxlength="200"
            class="form-input"
          ></u-input>
        </view>
        
        <!-- 报修地址 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="map" color="#409eff" size="16"></u-icon>
            <text>报修地址</text>
            <text class="required">*</text>
          </view>
          <view class="address-selector" @click="openHouseholdPicker">
            <view class="address-display">
              <text v-if="formData.householdId" class="selected-address">
                {{ getSelectedHouseholdLabel() }}
              </text>
              <text v-else class="placeholder">请选择房户</text>
            </view>
            <u-icon name="arrow-down" color="#999" size="16"></u-icon>
          </view>
        </view>
        
        <!-- 详细地址 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="location" color="#409eff" size="16"></u-icon>
            <text>详细地址</text>
          </view>
          <u-input 
            v-model="formData.repairAddress"
            placeholder="已根据选择的房户自动填充，可自行调整"
            maxlength="255"
            :disabled="false"
            class="form-input"
          ></u-input>
        </view>
          
        <!-- 故障描述 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="file-text" color="#409eff" size="16"></u-icon>
            <text>故障描述</text>
            <text class="required">*</text>
          </view>
          <u-textarea 
            v-model="formData.description"
            placeholder="请详细描述故障情况，包括故障发生时间、具体位置、现象等"
            maxlength="500"
            :auto-height="true"
            class="form-textarea"
          ></u-textarea>
        </view>
        
        <!-- 紧急程度 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="warning" color="#409eff" size="16"></u-icon>
            <text>紧急程度</text>
          </view>
          <view class="urgency-grid">
            <view 
              v-for="urgency in urgencyLevels" 
              :key="urgency.value"
              class="urgency-item"
              :class="{ active: formData.urgencyLevel === urgency.value }"
              @click="selectUrgencyLevel(urgency.value)"
            >
              <u-icon :name="urgency.icon" color="currentColor" size="16"></u-icon>
              <text>{{ urgency.label }}</text>
            </view>
          </view>
        </view>
        
        <!-- 联系电话 -->
        <view class="form-section">
          <view class="section-title">
            <u-icon name="phone" color="#409eff" size="16"></u-icon>
            <text>联系电话</text>
          </view>
          <u-input 
            v-model="formData.contactPhone"
            placeholder="请输入联系电话"
            maxlength="20"
            class="form-input"
          ></u-input>
        </view>
        
        <!-- 图片上传 -->
        <view class="form-section">
          <AppImageUpload
            v-model="formData.images"
            title="故障图片"
            tip="请上传故障现场图片，支持jpg、jpeg、png、gif、bmp、webp格式，最大10MB，最多9张"
            :max-count="9"
            :required="false"
            :max-size="10"
            :allowed-types="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']"
            @success="handleImageUploadSuccess"
            @error="handleImageUploadError"
            @remove="handleImageRemove"
            @preview="handleImagePreview"
          />
        </view>
      </u-form>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-section">
      <u-button 
        type="primary" 
        @click="submitRepair"
        :loading="submitting"
        class="submit-btn"
      >
        {{ submitting ? '提交中...' : '提交报修' }}
      </u-button>
      

    </view>

    <!-- 房户选择器 -->
    <view v-if="showHouseholdPicker" class="household-picker-overlay" @click="closeHouseholdPicker">
      <view class="household-picker-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择房户</text>
          <u-icon name="close" size="20" @click="closeHouseholdPicker"></u-icon>
        </view>
        
        <view v-if="householdList.length === 0" class="empty-state">
          <text class="empty-text">暂无房户数据</text>
        </view>
        <view v-else class="household-list">
          <view 
            v-for="(item, index) in householdList" 
            :key="item.householdId"
            class="household-item"
            @click="selectHousehold(index)"
          >
            <view class="household-info">
              <text class="household-name">{{ item.displayName }}</text>
              <text class="household-address">{{ item.fullAddress }}</text>
            </view>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { useAuthStore } from '@/store'
import { repairApi } from '@/api/repair'
import AppImageUpload from '@/components/AppImageUpload.vue'


export default {
  name: 'RepairService',
  
  components: {
    AppImageUpload
  },
  
  setup() {
    const authStore = useAuthStore()
    const formRef = ref(null)
    const submitting = ref(false)
    const showHouseholdPicker = ref(false)
    
    // 表单数据
    const formData = reactive({
      repairType: '',
      title: '',
      householdId: null,
      repairAddress: '',
      description: '',
      urgencyLevel: 'normal',
      contactPhone: '',
      images: []
    })
    
    // 监听formData.images变化
    watch(() => formData.images, (newVal, oldVal) => {
      console.log('repair.vue - formData.images变化:', { newVal, oldVal })
    }, { deep: true })
    
    // 表单验证规则
    const rules = {
      repairType: [
        { required: true, message: '请选择报修类型', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入报修标题', trigger: 'blur' },
        { min: 2, max: 200, message: '标题长度在2-200个字符之间', trigger: 'blur' }
      ],
      householdId: [
        { required: true, message: '请选择报修地址', trigger: 'change' }
      ],
      description: [
        { required: true, message: '请输入故障描述', trigger: 'blur' },
        { min: 10, max: 500, message: '描述长度在10-500个字符之间', trigger: 'blur' }
      ]
    }
    
    // 报修类型选项
    const repairTypes = [
      { label: '水电', value: 'water_electricity' },
      { label: '门窗', value: 'doors_windows' },
      { label: '电梯', value: 'elevator' },
      { label: '空调', value: 'air_conditioner' },
      { label: '其他', value: 'other' }
    ]
    
    // 紧急程度选项
    const urgencyLevels = [
      { label: '紧急', value: 'urgent', icon: 'error-circle' },
      { label: '一般', value: 'normal', icon: 'info-circle' },
      { label: '不紧急', value: 'low', icon: 'checkmark-circle' }
    ]
    
    // 房户数据
    const householdList = ref([])
    
    // 获取报修类型图标
    const getTypeIcon = (type) => {
      const iconMap = {
        water_electricity: 'flashlight',
        doors_windows: 'home',
        elevator: 'arrow-up',
        air_conditioner: 'snowflake',
        other: 'more-dot-fill'
      }
      return iconMap[type] || 'tools'
    }
    
    // 选择报修类型
    const selectRepairType = (type) => {
      formData.repairType = type
    }
    
    // 选择紧急程度
    const selectUrgencyLevel = (level) => {
      formData.urgencyLevel = level
    }
    
     // 获取房户列表
     const getHouseholdList = async () => {
       try {
         const response = await repairApi.getMyHouseholds()
         
         // 检查响应结构，可能是 response.data.data
         let householdData = []
         if (response && response.data) {
           // 如果response.data是数组，直接使用
           if (Array.isArray(response.data)) {
             householdData = response.data
           }
           // 如果response.data.data是数组，使用response.data.data
           else if (response.data.data && Array.isArray(response.data.data)) {
             householdData = response.data.data
           }
           // 如果response.data是对象且包含data字段
           else if (response.data && typeof response.data === 'object' && response.data.data) {
             householdData = response.data.data
           }
         }
         
         householdList.value = householdData
         
         // 确保每个房户项都有displayName字段
         if (householdList.value && householdList.value.length > 0) {
           householdList.value = householdList.value.map(item => ({
             ...item,
             displayName: item.displayName || `${item.communityName || ''}${item.buildingName || ''}${item.unitName || ''}${item.roomNumber || ''}`
           }))
         }
       } catch (error) {
         console.error('获取房户列表失败:', error)
         householdList.value = []
         uni.showToast({
           title: '获取房户列表失败',
           icon: 'none'
         })
       }
     }
    
    // 获取选中的房户标签
    const getSelectedHouseholdLabel = () => {
      const household = householdList.value.find(item => item.householdId === formData.householdId)
      if (household) {
        return household.displayName || `${household.communityName || ''}${household.buildingName || ''}${household.unitName || ''}${household.roomNumber || ''}`
      }
      return undefined
    }
    
    // 打开房户选择器
    const openHouseholdPicker = () => {
      
      // 确保有数据才打开选择器
      if (householdList.value && householdList.value.length > 0) {
        showHouseholdPicker.value = true
        
      } else {
        uni.showToast({
          title: '暂无房户数据',
          icon: 'none'
        })
      }
    }
    
    // 选择房户
    const selectHousehold = (index) => {
      const selectedItem = householdList.value[index]
      if (selectedItem && selectedItem.householdId) {
        formData.householdId = selectedItem.householdId
        formData.repairAddress = selectedItem.fullAddress || selectedItem.displayName || undefined
      }
      // 关闭选择器
      closeHouseholdPicker()
    }
    
    // 关闭房户选择器
    const closeHouseholdPicker = () => {
      showHouseholdPicker.value = false
    }
    
    // 选择图片
    const chooseImage = () => {
      uni.chooseImage({
        count: 9 - formData.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          formData.images.push(...res.tempFilePaths)
        }
      })
    }
    
         // 图片上传成功
     const handleImageUploadSuccess = (images) => {
       console.log('图片上传成功事件触发:', images)
       console.log('当前formData.images:', formData.images)
       console.log('图片上传成功 - 图片详情:', JSON.stringify(images, null, 2))
       console.log('图片上传成功 - formData.images详情:', JSON.stringify(formData.images, null, 2))
       uni.showToast({
         title: '图片上传成功',
         icon: 'success'
       })
     }
     
     // 图片上传失败
     const handleImageUploadError = (error) => {
       uni.showToast({
         title: '图片上传失败',
         icon: 'none'
       })
     }
     
     // 图片删除
     const handleImageRemove = (data) => {
       console.log('删除图片:', data)
     }
     
         // 图片预览
    const handleImagePreview = (data) => {
      console.log('预览图片:', data)
    }
    
    
    
    // 提交报修
    const submitRepair = async () => {
      try {
        // 表单验证
        const valid = await formRef.value.validate()
        if (!valid) return
        
        submitting.value = true
        
        // 显示提交进度提示
        uni.showLoading({
          title: '正在提交...',
          mask: true
        })
        
        // 调试：打印表单数据
        console.log('提交报修 - 表单数据:', formData)
        console.log('提交报修 - 图片列表:', formData.images)
        console.log('提交报修 - 图片数量:', formData.images.length)
        console.log('提交报修 - 图片列表详情:', JSON.stringify(formData.images, null, 2))
        
        // 处理图片数据 - 现在图片已经在选择时自动上传
        if (formData.images.length > 0) {
          console.log('处理已上传的图片，图片数量:', formData.images.length)
          
          // 检查是否有正在上传或上传失败的图片
          for (let i = 0; i < formData.images.length; i++) {
            const image = formData.images[i]
            console.log(`检查图片 ${i + 1}/${formData.images.length}:`, image)
            
            if (image.uploading) {
              console.error('存在正在上传的图片，请等待上传完成')
              uni.hideLoading()
              uni.showToast({
                title: '请等待图片上传完成',
                icon: 'none',
                duration: 3000
              })
              return
            }
            
            if (image.error) {
              console.error('存在上传失败的图片，请重新上传')
              uni.hideLoading()
              uni.showToast({
                title: '存在上传失败的图片，请重新上传',
                icon: 'none',
                duration: 3000
              })
              return
            }
          }
          
          console.log('所有图片检查完成，共处理:', formData.images.length, '张图片')
        } else {
          console.log('没有选择图片，跳过图片处理')
        }
        
        // 转换报修类型和紧急程度
        const repairTypeMap = {
          'water_electricity': 1,
          'doors_windows': 2,
          'elevator': 3,
          'air_conditioner': 4,
          'other': 5
        }
        
        const urgencyLevelMap = {
          'low': 1,
          'normal': 2,
          'urgent': 3
        }
        
        // 验证报修类型是否已选择
        if (!formData.repairType) {
          uni.hideLoading()
          uni.showToast({
            title: '请选择报修类型',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        // 验证报修类型映射
        const repairTypeValue = repairTypeMap[formData.repairType]
        if (!repairTypeValue) {
          uni.hideLoading()
          uni.showToast({
            title: '报修类型无效',
            icon: 'none',
            duration: 3000
          })
          return
        }
        
        // 提交报修数据
        const submitData = {
          title: formData.title,
          description: formData.description,
          householdId: formData.householdId,
          repairAddress: formData.repairAddress,
          repairType: repairTypeValue,
          urgencyLevel: urgencyLevelMap[formData.urgencyLevel],
          contactPhone: formData.contactPhone,
          // 后端期望imageList字段，包含图片URL列表
          imageList: formData.images.map(image => {
            // 提取图片URL，支持多种格式
            const imageUrl = image.url || image.fileUrl || image
            console.log('提取图片URL:', imageUrl, 'from image:', image)
            return imageUrl
          }).filter(Boolean) // 过滤掉空值
        }
        
        console.log('提交报修数据:', submitData)
        
        // 显示提交中状态
        uni.showLoading({
          title: '正在提交报修...',
          mask: true
        })
        
        // 调用报修提交API
        const result = await repairApi.submitRepair(submitData)
        
        // 隐藏加载提示
        uni.hideLoading()
        
        if (result && result.code === 200) {
          console.log('报修提交成功，工单ID:', result.data)
          
          uni.showToast({
            title: '报修提交成功',
            icon: 'success',
            duration: 2000
          })
          
          // 重置表单
          Object.assign(formData, {
            repairType: '',
            title: '',
            householdId: null,
            repairAddress: '',
            description: '',
            urgencyLevel: 'normal',
            contactPhone: '',
            images: []
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 2000)
        } else {
          throw new Error(result?.message || '提交失败')
        }
        
      } catch (error) {
        console.error('提交报修失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none',
          duration: 3000
        })
      } finally {
        submitting.value = false
      }
    }
    
    onMounted(() => {
      // 获取房户列表
      getHouseholdList()
      
    })
    
    return {
      formRef,
      formData,
      rules,
      submitting,
      showHouseholdPicker,
      householdList,
      repairTypes,
      urgencyLevels,
      getTypeIcon,
      selectRepairType,
      selectUrgencyLevel,
      getSelectedHouseholdLabel,
      openHouseholdPicker,
      selectHousehold,
      closeHouseholdPicker,
      handleImageUploadSuccess,
      handleImageUploadError,
      handleImageRemove,
      handleImagePreview,
      submitRepair
    }
  }
}
</script>

<style lang="scss" scoped>
/* 页面容器 */
.repair-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 服务说明区域 */
.intro-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  
  .intro-content {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .intro-text {
      flex: 1;
      font-size: 14px;
      color: #666;
      line-height: 1.4;
    }
  }
}

/* 表单容器 */
.form-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  margin: 0;
  padding: 16px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 表单区块 */
.form-section {
  margin-bottom: 24px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
    font-size: 15px;
    font-weight: 600;
    color: #333;
    
    .required {
      color: #f56c6c;
      font-weight: bold;
    }
  }
}

/* 报修类型网格 */
.type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 8px;
  
  .type-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px 8px;
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-color: #409eff;
      color: #fff;
    }
    
    text {
      font-size: 12px;
      text-align: center;
      word-break: break-word;
      line-height: 1.2;
    }
  }
}

/* 表单输入框 */
.form-input {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 表单文本域 */
.form-textarea {
  width: 100%;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
  min-height: 100px;
  
  &:focus {
    border-color: #409eff;
    background: #fff;
  }
}

/* 地址选择器 */
.address-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  
  .address-display {
    flex: 1;
    
    .selected-address {
      font-size: 14px;
      color: #333;
    }
    
    .placeholder {
      font-size: 14px;
      color: #999;
    }
  }
}

/* 紧急程度网格 */
.urgency-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  
  .urgency-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
    padding: 12px 8px;
    background: #f8f9fa;
    border: 2px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    
    &.active {
      background: linear-gradient(135deg, #409eff, #67c23a);
      border-color: #409eff;
      color: #fff;
    }
    
    text {
      font-size: 12px;
      text-align: center;
    }
  }
}



/* 提交按钮区域 */
.submit-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 16px;
  margin: 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  
  .submit-btn {
    width: 100%;
    height: 48px;
    background: linear-gradient(135deg, #409eff, #67c23a);
    border: none;
    border-radius: 24px;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
    
    &:active {
      transform: scale(0.98);
    }
  }
}

/* 房户选择器弹窗样式 */
.household-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.household-picker-popup {
  background: #fff;
  border-radius: 16px 16px 0 0;
  max-height: 70vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease-out;
  
  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    
    .popup-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }
  }
  
  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    
    .empty-text {
      font-size: 14px;
      color: #999;
    }
  }
  
  .household-list {
    flex: 1;
    overflow-y: auto;
    
    .household-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 20px;
      border-bottom: 1px solid #f8f8f8;
      transition: background-color 0.2s ease;
      
      &:active {
        background-color: #f5f5f5;
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      .household-info {
        flex: 1;
        margin-right: 12px;
        
        .household-name {
          display: block;
          font-size: 15px;
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }
        
        .household-address {
          display: block;
          font-size: 12px;
          color: #666;
          line-height: 1.4;
        }
      }
    }
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media screen and (max-width: 375px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 12px;
  }
  
  .type-grid {
    grid-template-columns: repeat(auto-fit, minmax(70px, 1fr));
    gap: 6px;
    
    .type-item {
      padding: 10px 6px;
      
      text {
        font-size: 11px;
      }
    }
  }
  
  .urgency-grid {
    gap: 6px;
    
    .urgency-item {
      padding: 10px 6px;
      
      text {
        font-size: 11px;
      }
    }
  }
  
  .form-input,
  .form-textarea,
  .address-selector {
    padding: 10px;
    font-size: 13px;
  }
  
  .household-picker-popup {
    .popup-header {
      padding: 12px 16px;
    }
    
    .popup-content {
      .household-list {
        .household-item {
          padding: 12px 16px;
          
          .household-info {
            .household-name {
              font-size: 14px;
            }
            
            .household-address {
              font-size: 11px;
            }
          }
        }
      }
    }
  }
}

@media screen and (min-width: 414px) {
  .intro-section,
  .form-container,
  .submit-section {
    padding: 20px;
  }
  
  .type-grid {
    grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
    gap: 10px;
  }
  
  .urgency-grid {
    gap: 10px;
  }
}
</style> 